window.onload = function () {
    //获取用户登录
    axios.defaults.withCredentials = true;
    //获取用户登录
    var user_id = ''
    var address_id=''
    var car_id=''
    var restaurant_id=''
  function xuanze(){ axios.get('https://elm.cangdu.org/v1/user').then(res => {
        // console.log(res);
        user_id = res.data.user_id
        // console.log(user_id);
        //获取收货地址列表
        $().ajax({
            url: `https://elm.cangdu.org/v1/users/${parseInt(user_id)}/addresses`,
            method: 'get',
           
            async: true,
            success: res => {
                // console.log(res);
              let kh_myaddresss=document.getElementsByClassName("kh_myaddresss")[0]
              kh_myaddresss.innerHTML=' '
               
               
                
               
                for (let i = 0; i < res.length; i++) {
                    var yoursex = ''
                    if (res[i].sex == 1) {
                        yoursex = '先生'
                    } else {
                        yoursex = '女士'
                    } 
                    // console.log(yoursex);
                    $create('kh_myaddresss', 'kh_youraddressbox',
                        `<div class='kh_yourchooseimg'></div>
                   
                   <div><span>${res[i].name} </span> 
                   <span class='kh_yoursexsex'>${yoursex}</span>
                   <span class='kh_yourphone12'>${res[i].phone} </span><br>
                   
                  
                   <span class='kh_tag'>${res[i].tag}</span> 
                   <span class='kh_addressstyle'>${res[i].address}</span>
                   
                   </div>`
                    )

                }
                let kh_yourchooseimg = document.getElementsByClassName("kh_yourchooseimg")
                
                let kh_youraddressbox = document.getElementsByClassName("kh_youraddressbox")
                let kh_chooseaddress=document.getElementsByClassName("kh_chooseaddress")[0]
                let kh_ensure=document.getElementsByClassName("kh_ensure")[0]
                kh_yourchooseimg[0].innerHTML = '<img src="/img/导航栏/选择.png">'
                for (let j = 0; j < kh_youraddressbox.length; j++) {
                    kh_youraddressbox[j].addEventListener('click', function () {
                        $('#kh_tochoose').html(`<span>${res[j].name} </span> 
                        <span class='kh_yoursexsex'>${yoursex}</span>
                        <span class='kh_yourphone12'>${res[j].phone} </span><p></p>
                        <span class='kh_tag'>${res[j].tag}</span> 
                        <span class='kh_addressstyle'>${res[j].address}</span>
                        `)
                        address_id=res[j].id
                        // console.log(address_id);
                        kh_chooseaddress.style.display='none'
                        kh_ensure.style.display="block"
                        for (let k = 0; k < kh_youraddressbox.length; k++) {
                           kh_yourchooseimg[k].innerHTML = ' '
                        }
                        kh_yourchooseimg[j].innerHTML = '<img src="/img/导航栏/选择.png">'
                    })

                }
            }
        })
        //登录后的图标变化
        if (res.data.status == 0) {
            $('#kh_tomyup').html(`登录/注册`).click(function () {
                window.location.href = `/pages/Singin/singin.html`
            })
        } else {
            $('#kh_tomyup').html(`<img src='/img/导航栏/个人.png' class='kh_gerentouxiang'>`).click(function () {
                window.location.href = `/pages/my/my.html`
            })
        }
    })}
    xuanze()



    //获取url内容
    let url = window.location.href;
    let paramStr = url.split('?')[1];
    let paramArr = paramStr.split('&');
    let paramObj = {};
    for (let i = 0; i < paramArr.length; i++) {
        let p_item = paramArr[i];
        paramObj[p_item.split('=')[0]] = p_item.split('=')[1]
    }
    // console.log(paramObj);
    //获取当前地址
    city_id = ''
    $().ajax({
        url: 'https://elm.cangdu.org/v1/cities?type=guess',
        method: 'get',
        success: res => {

            city_id = res.id

        }
    })
    //获取经纬度
    let geohash = '';
    //获取经纬度
    $().ajax({
        url: 'https://elm.cangdu.org/v1/cities/240',
        method: 'get',
        async: true,
        success: (res) => {
            // console.log(res);
            geohash = `${res.latitude},${res.longitude}`
            console.log(geohash);
        }

    })
    var psf = '';
    //获取餐馆详情
    // console.log(paramObj.id);
    $ajax({
        url: `https://elm.cangdu.org/shopping/restaurant/${paramObj.id}`,
        method: 'get',
        async: false,
        success: (res) => {
            psf = res.piecewise_agent_fee.tips
            console.log(res);
            restaurant_id=res.id
            let kh_restauranthead = document.getElementsByClassName("kh_restauranthead")
            let kh_right = document.getElementsByClassName("kh_right")

            $create("kh_restauranthead", "kh_headerBoximg",
                `<img src='//elm.cangdu.org/img/${res.image_path}'>`);
            $create("kh_restauranthead", "kh_headerBoxtext",
                `<span class='kh_nametext'>${res.name}</span>
        <span class="kh_tips">  
        商家配送/分钟送达/
         ${res.piecewise_agent_fee.tips}</span>
        <span class='kh_gonggao'>公告：${res.promotion_info}</span>`);
            $create("kh_restauranthead", 'kh_right', '>')

            kh_restauranthead[0].style.backgroundImage = 'url(' + `https://elm.cangdu.org/img/${res.image_path})`;
            kh_right[0].addEventListener('click', () => {
                window.location.href = `/pages/function/shangjiaxiangqin.html?id=${res.id}`
            })
        }

    })
    //切换选项卡
    let kh_goods = document.getElementById("kh_goods")
    let kh_content = document.getElementById("kh_content")
    kh_goods.classList.add("kh_blueborder")
    let kh_goodsBox = document.getElementsByClassName("kh_goodsBox")[0]
    let kh_contentBox = document.getElementsByClassName("kh_contentBox")[0]
    kh_goods.addEventListener('click', () => {
        kh_goodsBox.style.display = "block"
        kh_contentBox.style.display = "none"
        kh_goods.classList.add("kh_blueborder")
        kh_content.classList.remove("kh_blueborder")
    })
    kh_content.addEventListener('click', () => {
        kh_goodsBox.style.display = "none"
        kh_contentBox.style.display = "block"
        kh_goods.classList.remove("kh_blueborder")
        kh_content.classList.add("kh_blueborder")

    })
    //获取评价信息
    $ajax({
        url: `https://elm.cangdu.org/ugc/v2/restaurants/${paramObj.id}/ratings/scores`,
        method: 'get',
        async: false,
        success: (res) => {
            // console.log(res);
            $create('kh_Box1', 'kh_point',
                `<div class='kh_zhpj'>
            <span class='kh_zhpj1'>${paramObj.point}</span> <br>
            <span class='kh_zhpj2'>综合评价</span><br>
            <span class='kh_gaoyu'>高于周边商家${res.compare_rating.toFixed(3)*100}%</span>
            
            
            </div>
             <div class='kh_futd'>
             <div class='kh_bigtaxt1'>服务态度</div>
             <span class="iconfont" id='kh_xinxinxin'>&#xe641;&#xe641;&#xe641;&#xe641;&#xe641;
             ${res.service_score.toFixed(1)}
             </span>
             <div class='kh_bigtaxt1'>菜品评价</div>
             <span class="iconfont" id='kh_xinxinxin'>&#xe641;&#xe641;&#xe641;&#xe641;&#xe641;
             ${res.overall_score.toFixed(1)}
             </span>
             <div class='kh_bigtaxt1 kh_666' >送达时间</div>
             <span id='kh_777'>
             ${res.deliver_time}分钟
             </span>
             </div>
            `
            )

        }

    })
    //获取商品的分类信息
    $ajax({
        url: `https://elm.cangdu.org/ugc/v2/restaurants/${paramObj.id}/ratings/tags`,
        method: 'get',
        asyns: true,
        success: (res) => {
            // console.log(res)
            $create('kh_Box2', 'kh_contentfenlei',
                ` `)
            let kh_contentfenlei = document.getElementsByClassName("kh_contentfenlei")

            for (let i = 0; i < res.length; i++) {
                $create('kh_contentfenlei', 'kh_contentdiv',
                    `${res[i].name}(${res[i].count})`

                )
            }
            let kh_contentdiv = document.getElementsByClassName("kh_contentdiv")
            kh_contentdiv[0].style.backgroundColor = "#3190e8"
            kh_contentdiv[0].style.color = 'white'
            kh_contentdiv[2].style.backgroundColor = '#6666'
            for (let i = 0; i < res.length; i++) {
                kh_contentdiv[i].addEventListener('click', () => {
                    // console.log(i)

                    for (let i = 0; i < res.length; i++) {
                        kh_contentdiv[i].style.backgroundColor = "#ebf5ff"
                        kh_contentdiv[i].style.color = '#666666'
                    }
                    kh_contentdiv[2].style.backgroundColor = '#6666'
                    kh_contentdiv[i].style.backgroundColor = "#3190e8"
                    kh_contentdiv[i].style.color = 'white'

                })

            }


        }
    })

    //获取商品的评论信息
    $ajax({
        url: `https://elm.cangdu.org/ugc/v2/restaurants/${paramObj.id}/ratings?offset=0&limit=100`,
        method: 'get',
        // async:true,
        success: (res) => {
            // console.log(res);
            for (let i = 0; i < res.length; i++) {
                $create('kh_Box3', 'kh_contentsbox',
                    `<div class='kh_ueserimg'>
        <img src='//elm.cangdu.org/img/default.jpg'>
        </div>
        <div class='kh_uesercontent'>
        <span class='kh_uesername'>${res[i].username}</span><br>
        <span class="iconfont" id='kh_xinxinxin'>
        &#xe641;&#xe641;&#xe641;&#xe641;&#xe641;
        <span class='kh_uesercontentss'>${res[i].time_spent_desc}</span></span>
       
        </div>
        <div> <span class='kh_uesername1'>
        ${res[i].rated_at}
        </span></div>
        `
                )
            }
        }

    })


    let kh_goodsrank = document.getElementsByClassName("kh_goodsrank")
    let nav_index = 0;
    //食品榜单rank
    $ajax({
        url: `https://elm.cangdu.org/shopping/v2/menu?restaurant_id=${paramObj.id}`,
        method: 'get',
        async: true,
        success: (res) => {
            for (let i = 0; i < res.length; i++) {
                let ranks = $().create('div').addClass('kh_ranks').html(`<div class='kh_goodsnum'><span class='kh_num'>0</span></div>${res[i].name}`)
                    .attr('data-index', i);
                $('.kh_goodsrank').append(ranks);
                ranks.el.onclick = function () {
                    nav_index = $(this).attr('data-index');
                    let top = $('.kh_rankhead').eq(nav_index).el.offsetTop;
                    rolling(0, top, 5, $('.kh_goodsshow').el)
                }
            
                let kh_ranks = document.getElementsByClassName("kh_ranks")
                // console.log(kh_ranks.length);
                kh_ranks[0].classList.add("kh_rankstyle")
                for (let i = 0; i < kh_ranks.length; i++) {
                    kh_ranks[i].addEventListener('click', () => {
                        // console.log(i);
                        for (let i = 0; i < kh_ranks.length; i++) {
                            kh_ranks[i].classList.remove("kh_rankstyle")
                        }
                        kh_ranks[i].classList.add("kh_rankstyle")
                    })

                }
            }
        }
    })
    //rank样式
    var footsData = [];
    var gowcargoods = []
    var gwccar = []

    //食品展示
    $ajax({
        url: `https://elm.cangdu.org/shopping/v2/menu?restaurant_id=${paramObj.id}`,
        method: 'get',
        async: true,
        success: (res) => {
            // console.log(res);
            footsData = res;
            for (let i = 0; i < res.length; i++) {
                let wrap = $('.kh_goodsshow');
                let rankhead = $().create('div').addClass('kh_rankhead');
                let goodstitle = $().create('div').addClass('kh_goodstitle').attr('id', res[i].id).html(res[i].name);
                let description = {};
                if (res[i].description !== '') {
                    description = $().create('span').addClass('kh_description').html(res[i].description);
                } else {
                    description = $().create('span').addClass('kh_description');
                }
                $(wrap).append(rankhead);
                rankhead.append(goodstitle);
                goodstitle.append(description)

                for (let j = 0; j < res[i].foods.length; j++) {
                    var data = [];
                    let f_item = res[i].foods[j];
                    let goodsbody = {};
                    if (res[i].foods[j].name !== '') {
                        goodsbody = $().create('div').addClass('kh_goodsbody').html(
                            `<div class='kh_goodsimg1'>
                            <img src='https://elm.cangdu.org/img/${f_item.image_path}'
                            </div><div class='kh_goddsname'>
                            <span class=''>
                            ${f_item.name}</span><br>
                            <span class='kh_yueshoutext'>${f_item.description}</span><br>
                            <span class='kh_yueshoutext'>月售：${f_item.month_sales}份 好评率${f_item.satisfy_rate}%</span></div><br>
                            <div class='kh_joinshopcar'><span>￥${f_item.specfoods[0].price}</span> 
                            <div id='kh_delgoodnum'><div id='kh_deladd'>—</div><span id="kh_numadd"></span></div>
                           
                            <div class='kh_addtoshopcar' id='kh_addtoshopcar'>+</div>
                            </div>
                            `).on('click', function () {
                            // window.location.href =
                            // `/pages/function/foods.html?name=${f_item.name}&img=${f_item.image_path}&rating=${f_item.rating}&count=${f_item.rating_count}&sales=${f_item.month_sales}&rate=${f_item.satisfy_rate}`
                        });
                        // data[j]=
                    } else {
                        goodsbody = $().create('div').addClass('kh_goodsbody');
                    }
                    $(goodsbody).attr('data-id', f_item.item_id)
                    goodstitle.append(goodsbody);
                }
            }

            let classifyNodes = $('.kh_goodstitle').el;
            let kh_num = document.getElementsByClassName("kh_num")
            let kh_goodsnum = document.getElementsByClassName('kh_goodsnum')
            let kh_gwcnum = document.getElementById("kh_num")
            let kh_gwcimg = document.getElementById("kh_gwcimg")
            let kh_lastgo = document.getElementById("kh_lastgo")
            let kh_psf = document.getElementById("kh_psf")
            let kh_price = document.getElementById("kh_price")
            let kh_addtoshopcar = document.getElementsByClassName("kh_addtoshopcar")
            kh_psf.innerHTML = psf
            var num = 0;
            var pirce = 0;
            var numadd = 0;
            for (let i = 0; i < classifyNodes.length; i++) {
                let kh_goodsnum = classifyNodes[i].querySelectorAll("#kh_goodsnum")
                let foodNodes = classifyNodes[i].querySelectorAll('.kh_goodsbody');

                for (let j = 0; j < foodNodes.length; j++) {
                    let addtoCarNode = foodNodes[j].querySelector('#kh_addtoshopcar');
                    let addnum = foodNodes[j].querySelector('#kh_delgoodnum');
                    let kh_deladd = foodNodes[j].querySelector('#kh_deladd');
                    let kh_numadd = foodNodes[j].querySelector('#kh_numadd');

                    var numgoods = 0;
                    var flag = false;
                    //购物车清单显示
                    $('#kh_gwcimg').click(function () {
                        flag = !flag;
                        if (flag) {
                            $('.kh_gwcgoodsshow').show();
                        } else {
                            $('.kh_gwcgoodsshow').hidden();
                        }
                    })
                    //

                    $(foodNodes[j]).on('click', function (e) {
                        if (e.target == addtoCarNode) {
                            let id_this = $(this).attr('data-id');
                            let this_location = getThis(id_this);
                            let this_index = inCart(id_this);
                            if (this_location !== -1) {
                                if (inCart(id_this) !== -1) {
                                    // console.log(this_index);
                                    // console.log(gowcargoods);

                                    gowcargoods[this_index].quantity += 1;
                                } else {
                                    gowcargoods.push({
                                        attrs: [],
                                        extra: {},
                                        id: footsData[i].foods[j].item_id,
                                        name: footsData[i].foods[j].specfoods[0].name,
                                        packing_fee: footsData[i].foods[j].specfoods[0].packing_fee,
                                        price: footsData[i].foods[j].specfoods[0].price,
                                        quantity: 1,
                                        sku_id: footsData[i].foods[j].specfoods[0].sku_id,
                                        specs: footsData[i].foods[j].specfoods[0].specs,
                                        stock: footsData[i].foods[j].specfoods[0].stock
                                    })
                                }

                                kh_deladd.onclick = () => {
                                    gowcargoods[this_index].quantity -= 1
                                    console.log(gowcargoods[this_index].quantity);
                                    price()
                                    showNum(this_location, this_index);

                                    $('.kh_gowucarshow').el.innerHTML = '';

                                    //渲染数据
                                    for (let z = 0; z < gowcargoods.length; z++) {
                                        $('.kh_gowucarshow').append($().create('div').addClass('kh_goodsshows').html(
                                            `<div class='kh_goodsa'><span>${gowcargoods[z].name}</span>
                                  <span class="kh_color">￥${gowcargoods[z].price*gowcargoods[z].quantity}</span>
                                  <span>${gowcargoods[z].quantity}个</span>
                                  </div>
                                    `
                                        ))
                                    }

                                }
                            }

                            //清空购物车
                            $('#kh_clearALL').click(function () {
                                window.location.href = `restaurant.html?id=3276&point=4.1&psf=配送费约¥5`


                            })
                            showNum(this_location, this_index);
                            price()


                            $('.kh_gowucarshow').el.innerHTML = '';
                            //渲染数据
                            for (let z = 0; z < gowcargoods.length; z++) {
                                $('.kh_gowucarshow').append($().create('div').addClass('kh_goodsshows').html(
                                    `<div class='kh_goodsa'><span>${gowcargoods[z].name}</span>
                                  <span class="kh_color">￥${gowcargoods[z].price*gowcargoods[z].quantity}</span>
                                  <span>${gowcargoods[z].quantity}个</span>
                                  </div>
                                    `
                                ))
                            }

                            function carShowInit() {
                                let caritems = $('.kh_gowucarshow').child('.kh_goodsshows');
                                for (let y = 0; y < caritems.el.length; y++) {
                                    const carItem = caritems.el[y];
                                    // console.log(carItem);
                                    $('.kh_gowucarshow').remove(carItem);
                                    // console.log(carItem);
                                }
                            }

                        }


                    })

                    // 判断购物车是否有该商品, 有就只改数量,没有就显示添加后的数量
                    function showNum(obj, car_index) {
                        if (car_index == -1) {
                            addnum.style.display = "block";
                            kh_numadd.innerHTML = gowcargoods[gowcargoods.length - 1].quantity;
                        } else if (gowcargoods[car_index].quantity < 1) {
                            gowcargoods.splice(car_index, 1);
                            // console.log(gowcargoods);
                            addnum.style.display = "none";
                        } else {
                            kh_numadd.innerHTML = gowcargoods[car_index].quantity;
                        }
                    }


                    //购物车价格显示
                    function price() {
                        var price = 0
                        var num = 0
                        for (let k = 0; k < gowcargoods.length; k++) {
                            price = price + (gowcargoods[k].quantity * gowcargoods[k].price)
                            // console.log(price);
                            num = num + (gowcargoods[k].quantity)
                            kh_price.innerHTML = price
                        }
                        if (price >= 20) {
                            kh_lastgo.innerHTML = '去结算'
                            kh_lastgo.style.backgroundColor = '#4cd964'
                        } else {
                            kh_lastgo.style.backgroundColor = '#535356'
                            kh_lastgo.innerHTML = '还差' + (20 - price) + '元起送'

                        }
                        if (num > 0) {
                            kh_gwcnum.style.display = "block"
                            kh_gwcnum.innerHTML = num;
                            kh_gwcimg.style.backgroundColor = '#3190e8'
                        } else if (num <= 1) {
                            kh_gwcnum.style.display = "none"
                            kh_gwcnum.innerHTML = num;
                            kh_gwcimg.style.backgroundColor = '#333'
                            kh_lastgo.style.backgroundColor = '#535356'
                        }


                    }
                    // 判断点击的在数据数组中的位置,没有就返回-1
                    function getThis(item_id) {
                        for (let m = 0; m < footsData.length; m++) {
                            let item_t = footsData[m];
                            let flag = false;
                            for (let n = 0; n < item_t.foods.length; n++) {
                                let item_f = item_t.foods[n];
                                if (item_f.item_id == item_id) {
                                    flag = true;
                                    return {
                                        i: m,
                                        j: n
                                    }
                                }
                            }
                            if (!flag) {
                                return -1;
                            }
                        }
                    }
                    // 判断在购物车中的位置,有就返回下标,没有就返回-1
                    function inCart(item_id) {
                        let flag = -1;
                        for (let m = 0; m < gowcargoods.length; m++) {
                            let car_item = gowcargoods[m];
                            // console.log(item_id);
                            if (car_item.id == item_id) {
                                flag = true;
                                return m;
                            }
                        }
                        return flag;
                    }
                    let kh_none = document.getElementsByClassName("kh_none")[0]
                    let kh_ensure = document.getElementsByClassName("kh_ensure")[0]
                    let kh_choosea = document.getElementById("kh_choosea")
                    let kh_chooseaddress = document.getElementsByClassName("kh_chooseaddress")[0]
                    let kh_tianjiaaddress = document.getElementsByClassName("kh_tianjiaaddress")[0]
                    let kh_searchaddress = document.getElementsByClassName("kh_searchaddress")[0]
                   
                    //加入购物车
                    $('#kh_lastgo').click(function () {


                        kh_none.style.display = "none"
                        kh_ensure.style.display = "block"
                        $('#kh_backtonone').click(function () {
                            kh_none.style.display = "block"
                            kh_ensure.style.display = "none"
                        })
                        $('#kh_tochoose').click(function () {
                            kh_ensure.style.display = 'none'
                            kh_chooseaddress.style.display = "block"
                        })
                        $("#kh_choosea").click(function () {
                            kh_ensure.style.display = 'block'
                            kh_chooseaddress.style.display = "none"

                        })
                        $('.kh_add').click(function () {
                            kh_chooseaddress.style.display = "none"
                            kh_tianjiaaddress.style.display = 'block'
                        })
                        $('#kh_backtochoose').click(function () {
                            kh_chooseaddress.style.display = "block"
                            kh_tianjiaaddress.style.display = 'none'
                        })
                        $('#kh_youraddress1').click(function () {
                            kh_tianjiaaddress.style.display = 'none'
                            kh_searchaddress.style.display = "block"
                        })
                        $("#kh_backtotianjia").click(function () {
                            kh_tianjiaaddress.style.display = 'block'
                            kh_searchaddress.style.display = "none"
                        })



                        $().ajax({
                            url: `https://elm.cangdu.org/v1/carts/checkout`,
                            method: 'POST',
                            data: {
                                restaurant_id: paramObj.id,
                                geohash: geohash,
                                entities: [gowcargoods]
                            },
                            success: res => {
                                console.log(res);
                                car_id=res.id
                                $('#kh_delivery_reach_time').html(`${res.delivery_reach_time}到达`)
                                $('#kh_xiaopic').attr('src', `//elm.cangdu.org/img/${res.cart.restaurant_info.image_path}`)
                                $('#kh_name1').html(`${res.cart.restaurant_info.name}`)
                                price1 = 0
                                $('.kh_ordershow').html(` `)
                                for (let h = 0; h < res.cart.groups[0].length; h++) {
                                      console.log( res.cart.groups[0][h]);
                                    $create('kh_ordershow', 'kh_ordernum',
                                        `<div>${res.cart.groups[0][h].name}</div>
                              <div class='kh_margin'><span class='kh_colorx'>X${res.cart.groups[0][h].quantity}</span>
                              <span>￥${res.cart.groups[0][h].price}</span></div>
                              `
                                    )
                                    price1 += res.cart.groups[0][h].quantity * res.cart.groups[0][h].price

                                }
                                
                                $('#kh_canhef').html(`￥${res.cart.original_total-res.cart.deliver_amount- price1}`)
                                $('#kh_psf2').html(`￥${res.cart.deliver_amount}`)
                                $('.kh_accountm').html(`￥${res.cart.original_total}`)
                                $('.kh_accountm1').html(`￥${res.cart.original_total}`)
                                $('.kh_accountm2').html(`￥${res.cart.original_total}`)
                                $('.kh_address1').click(function () {

                                })
                                // window.localStorage.setItem('location', [gowcargoods]);
                                // window.location.href=`/pages/ensureorder/ensure.html?id=${paramObj.id}&geohash=${geohash}&entities=${gowcargoods}`
                            }
                        })

                    })




                }
            }


        }
    })
    //性别

    var sex = 1

    $('#kh_man').click(function () {
        $('#kh_man').attr('src', '/img/导航栏/选择.png')
        $('#kh_woman').attr('src', '/img/导航栏/未选择.png')
        sex = 1
        console.log(sex);
    })

    $('#kh_woman').click(function () {

        $('#kh_man').attr('src', '/img/导航栏/未选择.png')
        $('#kh_woman').attr('src', '/img/导航栏/选择.png')
        sex = 2
        console.log(sex);
    })
    //获取keywords
    let kh_searchinput = document.getElementById("kh_searchinput")
    let kh_cityshow = document.getElementsByClassName("kh_cityshow")[0]

    //搜索地址
    $('#kh_up').on('click', function () {

        $().ajax({
            url: `https://elm.cangdu.org/v1/pois?city_id=240&keyword=${kh_searchinput.value}&type=search`,
            method: 'GET',
            success: res => {
                console.log(res);
                kh_cityshow.innerHTML = ''
                if (res.length == 0) {
                    $create('kh_cityshow', 'kh_addressBox',
                        `暂无该地址`
                    )
                }
                if (res.length > 0) {
                    for (let i = 0; i < res.length; i++) {

                        $create('kh_cityshow', 'kh_addressBox',
                            `<span class='kh_addressname'>${res[i].name}</span><br>
                <span class='kh_address'>${res[i].address}</span>`
                        )
                        let kh_addressBox = document.getElementsByClassName('kh_addressBox')
                        // for (let i = 0; i < res.length; i++) {
                        //     kh_addressBox[i].addEventListener('click',()=>{
                        //           window.location.href=`/pages/address/newaddress.html?geohash=${res[i].geohash}`

                        //     })

                        // }

                    }
                } else {
                    $create('kh_cityshow', 'kh_addressBox',
                        `请输入地址`
                    )

                }
                // 点击跳转传送地址
                let kh_youraddress1 = document.getElementById("kh_youraddress1")
                let kh_addressBox = document.getElementsByClassName("kh_addressBox")

                let kh_addressname = document.getElementsByClassName("kh_addressname")
                for (let i = 0; i < res.length; i++) {
                    kh_addressBox[i].addEventListener('click', () => {
                        kh_youraddress1.value = kh_addressname[i].innerHTML
                        kh_cityshow.innerHTML = ''
                        kh_searchinput.value = ''
                        let kh_tianjiaaddress = document.getElementsByClassName("kh_tianjiaaddress")[0]
                        let kh_searchaddress = document.getElementsByClassName("kh_searchaddress")[0]
                        $create('kh_cityshow', 'kh_addressBox',
                            `  `)
                        kh_searchaddress.style.display = 'none'
                        kh_tianjiaaddress.style.display = 'block'
                    })


                }






            }

        })
    })

    //添加地址
    $('#kh_yourups').click(function () {
        $().ajax({
            url: `https://elm.cangdu.org/v1/users/${user_id}/addresses`,
            method: 'post',
            async: true,
            data: {
                user_id: parseInt(user_id),
                address: $('#kh_youraddress1').value(),
                address_detail: $('#kh_yourgpss').value(),
                geohash: geohash,
                name: $('#kh_yournames').value(),
                phone: $('#kh_yournumber').value(),
                tag: $('#kh_yourtips').value(),
                sex: sex,
                phone_bk: $('#kh_phoneor').value(),
                tag_type: 2,
            },
            success: res => {
                console.log(res);
                let kh_tianjiaaddress=document.getElementsByClassName("kh_tianjiaaddress")[0]
                let kh_chooseaddress=document.getElementsByClassName("kh_chooseaddress")[0]
                kh_tianjiaaddress.style.display="none"
                kh_chooseaddress.style.display="block"


            }
        })
        xuanze()
    })
    //下单了
    $('#kh_ensurein').click(function(){
        $().ajax({
        url:`https://elm.cangdu.org/v1/users/${user_id}/carts/${car_id}/orders`,
        method:'post',
        async:true,
        data:{
            user_id:user_id ,
            cart_id:car_id,
            address_id:address_id,
            restaurant_id :restaurant_id ,
            geohash:geohash,
            description:'无',
            entities:[gowcargoods]
        },
        success:res=>{
            Toast('warning','<div class="kh_fsl1">暂不开放支付功能</div>')
            timer()
            console.log(res);
            let kh_mypay=document.getElementsByClassName("kh_mypay")[0]
            let kh_ensure = document.getElementsByClassName("kh_ensure")[0]
            kh_ensure.style.display="none"
            kh_mypay.style.display="block"
            $("#kh_backtoensure").click(function(){
                kh_ensure.style.display="block"
                kh_mypay.style.display="none"
            })
            // window.location.href='/pages/order/order.html'
        }
    }) 
    })
    //选择支付方式
    
    $('#kh_zfbimg').click(function(){
        $('#kh_zfbimg').attr('src','/img/导航栏/选择.png')
        $('#kh_vximg').attr('src','/img/导航栏/未选择.png')
        Toast('warning','<div class="kh_fsl">当前环境无法支付,请打开官方APP进行付款</div>')
    })
    $('#kh_vximg').click(function(){
        $('#kh_zfbimg').attr('src','/img/导航栏/未选择.png')
        $('#kh_vximg').attr('src','/img/导航栏/选择.png')
        Toast('warning','<div class="kh_fsl">当前环境无法支付,请打开官方APP进行付款</div>')
    })
    //跳转到订单列表
    $('#kh_ensurepay').click(function(){
        window.location.href='/pages/order/order.html'
    })
    
    


     
function timer(){

    var minuteNum = 14;
    var secondNum = 59;
    timeShowDisplay(minuteNum,secondNum);
    let countTime = setInterval(function(){
        if(minuteNum == 0){
            clearInterval(minuteNum);
        }else{
            if(secondNum == 0){
                secondNum = 59;
                minuteNum -= 1;
            }else{
                secondNum -= 1;
            }
        }
        timeShowDisplay(minuteNum,secondNum);
    },1000)
    function timeShowDisplay(minute,second){
        if(minute < 10){
            $('.kh_count>.kh_minute').html('0'+minute);
        }else{
            $('.kh_count>.kh_minute').html(minute);
        }
        if(second < 10){
            $('.kh_count>.kh_second').html('0'+second);
        }else{
            $('.kh_count>.kh_second').html(second);
        }
    }
}


    function rolling(X, Y, speed, scrollItem) {
        let scrollY = 0;
        if (!speed) {
            speed = 10;
        } else if (typeof speed === 'number' || typeof speed === 'string') {
            speed = parseInt(speed)
        } else {
            new Error('请输入正确的速度，仅支持string、十进制的Number类型整数');
        }
        if (!scrollItem) {
            scrollItem = window;
        }

        function start() {
            if (scrollY < Y - 2) {
                scrollY += (Y - scrollY) / speed;
                setTimeout(() => {
                    scrollItem.scrollTo(X, scrollY);
                    start();
                }, 18);
            } else {
                scrollY = 0;
                scrollItem.scrollTo(X, Y);
            }
        }
        setTimeout(() => {
            start();
        }, 100);
    }












       





              
    



}


           



